package com.fita.admin.web.controller.agent;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.fita.admin.entity.search.agent.AgentAuditSearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.DataService;
import com.fita.admin.service.agent.AgentAuditService;
import com.fita.admin.service.authority.PrincipalService;
import com.fita.admin.web.resolver.Secure;
import com.fita.entity.agent.AgentApply;
import com.fita.entity.agent.AgentApplyStatus;
import com.fita.entity.agent.AgentCompany;
import com.fita.entity.principal.District;
import com.fita.entity.principal.Principal;
import org.apache.commons.collections.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 代理员审核管理
 *
 * @author Ark
 *
 */
@Controller
@RequestMapping("/agent-audits")
@MenuSetting("menu-agent")
public class AgentAuditController {

	private static final Logger logger = LoggerFactory.getLogger(AgentAuditController.class);

	@Autowired
	private AgentAuditService agentAuditService;
	
	@Autowired
	@Qualifier("dataService")
	private DataService<District> dataService;
	
	@Autowired
	private PrincipalService principalService;
	
	/**
     * list
     * 
     * @param status
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-agent-audit")
    public ModelAndView list(@RequestParam(name = "status", defaultValue = "AUTHING") AgentApplyStatus status, Page page, @Secure Login login, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-list");
       
        int totals = agentAuditService.count(status, login);
       
        modelAndView.addObject("status", status);
        
        if (totals > 0) {
        	
            List<AgentApply> agentApplies = agentAuditService.list(status, page.with(totals), login);
           
            modelAndView.addObject("agentApplies", agentApplies);
            
            modelAndView.addObject("page", page);
        }
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
        	return modelAndView;
    }
	
	/**
	 * 显示查询面板
	 * @param status
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-agent-audit")
	public ModelAndView search(@RequestParam("status") AgentApplyStatus status) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-search");
		
		modelAndView.addObject("status", status);
		
		return modelAndView;
	}

	/**
	 *  on search
	 * @param search
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-agent-audit")
	public ModelAndView onSearch(@RequestParam("status") AgentApplyStatus status,AgentAuditSearch search, HttpServletRequest request, Page page, @Secure Login login) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-list");
		modelAndView.addObject("status", status);
		int totals = agentAuditService.count(search,login);
		if (totals > 0) {
			List<AgentApply> agentApplies = agentAuditService.search(search, page.with(totals), login);
			modelAndView.addObject("agentApplies", agentApplies);
			modelAndView.addObject("page", page);
			modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter","status"));
		}
		return modelAndView;
	}
	
	/**
	 * 显示修改面板
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public ModelAndView edit(@PathVariable Long id) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-edit");
		AgentApply agentApply = agentAuditService.load(AgentApply.class, id);
		modelAndView.addObject("agentApply", agentApply);
		
		return modelAndView;
	}
	
	/**
	 * 
	 * @param agentApply
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onEdit(@PathVariable Long id, AgentApply agentApply) {
		
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.edit(id, agentApply);
			httpResult.success().message("修改成功");	
		} catch (BusinessException e) {
			logger.error("onEdit occurs error: ", e);
			httpResult.fail(e.getCode()).message(e.getMessage());
        } catch (Exception e) {
			 logger.error("#onEdit() - agentAudit team fail, exception is [{}]", e);
	         httpResult.fail("500").message("修改失败");
		}
		return httpResult;
	}
	
	/**
	 * 显示驳回面板
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/reject", method = RequestMethod.GET)
	@MenuSetting("submenu-agent-audit")
	public ModelAndView reject(@PathVariable Long id) {
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-reject");
		modelAndView.addObject("id", id);
		return modelAndView;
	}

	/**
	 * 驳回
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/reject", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onReject(@PathVariable Long id) {
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.reject(id);
			httpResult.success().message("驳回成功");
		} catch (Exception e) {
			logger.error("onReject occurs error", e);
			httpResult.fail("500").message("驳回失败");
		}
		return httpResult;
	}
	
	/**
	 * 显示激活面板
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/activate", method = RequestMethod.GET)
	public ModelAndView activate(@PathVariable Long id) {
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-activate");
		modelAndView.addObject("id", id);
		return modelAndView;

	}
	
	/**
	 * 激活
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/activate", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onActivate(@PathVariable Long id) {
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.activate(id);
			httpResult.success().message("激活成功");
			
		} catch (Exception e) {
			logger.error("onActivate occurs error", e);
			httpResult.fail("500").message("激活失败");
		}
		return httpResult;
		
		
	}
	
	/**
	 * 显示审核通过面板
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/verified", method = RequestMethod.GET)
	public ModelAndView verified(@PathVariable Long id) {
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-verified");
		modelAndView.addObject("id", id);
		return modelAndView;
		
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/verified", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public  HttpResult onVerified(@PathVariable Long id) {
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.verified(id);
			httpResult.success().message("审核通过");
			
		} catch (BusinessException e) {
			logger.error("onVerified occurs error: ", e);
			httpResult.fail(e.getCode()).message(e.getMessage());
		} catch (Exception e) {
			logger.error("onVerified occurs error", e);
			httpResult.fail("500").message("审核通过失败");
		}
		return httpResult;
	}
	
	/**
	 * 分派公司
	 * @return
	 */
	@RequestMapping(value = "/{id}/assignCompany", method = RequestMethod.GET)
	public ModelAndView assignCompany(@PathVariable Long id) {
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-assignCompany");
		List<AgentCompany> agetnCompanies = agentAuditService.listAgentCompany();
		modelAndView.addObject("agetnCompanies", agetnCompanies);
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/assignCompany", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onAssignCompany(@PathVariable("id") Long id, @RequestParam Long companyId) {
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.assignCompany(id, companyId);
			httpResult.success().message("分配公司成功");
		} catch (Exception e) {
			logger.error("onAssignCompany occurs error", e);
			httpResult.fail("500").message("分配公司失败");
		}
		return httpResult;
	}
	
	/**
	 * 显示详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@MenuSetting("submenu-agent-audit")
	public ModelAndView view(@PathVariable Long id) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-view");

		AgentApply agentApplies = agentAuditService.load(AgentApply.class, id);

		modelAndView.addObject("agentApplies", agentApplies);
		return modelAndView;
	}
	
	/**
	    * 显示指定销售面板
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/{id}/principal", method = RequestMethod.GET)
	public ModelAndView principal(@PathVariable Long id, @Secure Login login) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-principal");
		
	    AgentApply agentApply = agentAuditService.load(AgentApply.class, id);

		List<Principal> principals = null;
		
		if (login.isAdmin()) {
		    
            principals = principalService.list(ListUtils.EMPTY_LIST, agentApply.getDistrict());
        }
		if (login.isSaleDirector()) {
		    
		    List<String> authorities = new ArrayList<String>();
		    
		    authorities.add("SALE_DIRECTOR");
		    
		    authorities.add("SALE_USER");
		    
		    principals = principalService.list(authorities, login.getDistrict());
        }
	 	modelAndView.addObject("principals", principals);
	 	
	 	modelAndView.addObject("agentApply", agentApply);
	 	
		modelAndView.addObject("id", id);
		
		return modelAndView;
		}
	
	/**
	   * 指定销售
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/principal", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onPrincipal(@PathVariable Long id,@RequestParam(required = true) Long principalId) {
		
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.principal(id, principalId);
			httpResult.success().message("指定销售成功");
		} catch (Exception e) {
			logger.error("onPrincipal occurs error", e);
			httpResult.fail("500").message("指定销售失败");
		}
		return httpResult;
	}
	
	/**
	 * 切换分区
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/district", method = RequestMethod.GET)
	public ModelAndView district(@PathVariable Long id) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-district");
		List<District> district = dataService.loadAll(District.class);
		modelAndView.addObject("district", district);
		modelAndView.addObject("id", id);
		return modelAndView;
		
	}
	
	/**
	 * 切换分区
	 * @param id
	 * @param districtId
	 * @return
	 */
	@RequestMapping(value = "/{id}/district", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onDistrict(@RequestParam(name = "status", defaultValue = "AUTHING") AgentApplyStatus status, @PathVariable Long id, @RequestParam Long districtId) {
		
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.district(id, districtId, status);
			httpResult.success().message("切换分区成功");
		} catch (Exception e) {
			logger.error("onDistrict occurs error", e);
			httpResult.fail("500").message("切换分区失败");
		}
		return httpResult;
		}
	
	/**
	 * 更换销售
	 * @return
	 */
	@RequestMapping(value = "/{id}/editPrincipal", method = RequestMethod.GET)
	public  ModelAndView editPrincipal(@PathVariable Long id, @Secure Login login, Page page) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-edit-principal");
		AgentApply agentApply = agentAuditService.load(AgentApply.class, id);
		List<Principal> principal = agentAuditService.list(login, page, agentApply.getDistrict().getId());
	 	modelAndView.addObject("principal", principal);
		modelAndView.addObject("id", id);
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @param principalId
	 * @return
	 */
	@RequestMapping(value = "/{id}/editPrincipal", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onEditPrincipal(@PathVariable Long id, @RequestParam Long principalId) {
		
		HttpResult  httpResult = new HttpResult();
		try {
			agentAuditService.principal(id, principalId);
			httpResult.success().message("更换销售成功");
		} catch (Exception e) {
			logger.error("onEditPrincipal occurs error", e);
			httpResult.fail("500").message("更换销售失败");
		}
		return httpResult;
	}
	
	/**
	 * 冻结
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/frost", method = RequestMethod.GET)
	public ModelAndView frost(@PathVariable Long id) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-frost");
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/frost", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
	public HttpResult onFrost(@PathVariable Long id) {
		
		HttpResult httpResult = new HttpResult();
		try {
			agentAuditService.frost(id);
			httpResult.success().message("冻结成功");
		} catch (Exception e) {
			logger.error("onFrost occurs error", e);
			httpResult.fail("500").message("冻结失败");
		}
		
		return httpResult;
	}
	
	/**
	 * 激活
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/activation", method = RequestMethod.GET)
	public ModelAndView activation(@PathVariable Long id) {
		
		ModelAndView modelAndView = new ModelAndView("agent/audit/agent-audit-activation");
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/activation", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public HttpResult onActivation(@PathVariable Long id) {
		
		HttpResult httpResult = new HttpResult();
		
		try {
			agentAuditService.activation(id);
			httpResult.success().message("激活成功");
		} catch (Exception e) {
			logger.error("onActivation occurs error", e);
			httpResult.fail("500").message("激活失败");
		}
		
		return httpResult;
	}
	
}
